import os
import ctypes
from ctypes import *
from ctypes.util import find_library
import time


# 定义结构，继承自ctypes.Structure，与C语言中定义的结构对应
class Point(ctypes.Structure):
  _fields_ = [
    ('x', ctypes.c_double), 
    ('y', ctypes.c_double)
  ]

class Test(ctypes.Structure):
  _fields_ = [
    ('sentence', ctypes.c_char_p),
    ('nb_points', ctypes.c_int),
    ('points', ctypes.POINTER(Point)),
    ('distances', ctypes.POINTER(c_double)),
  ]

so_path = os.path.abspath(".")
so_path = os.path.join(so_path, "./jiasu.so")
so = ctypes.CDLL(so_path)


if __name__ == '__main__':

  start_time = time.time()
  # 创建
  test = {}
  test['sentence'] = "A nice sentence to test.".encode('utf-8')
  test['nb_points'] = 0
  test['points'] = None
  test['distances'] = None
  c_test = Test(**test)
  ptr_test = ctypes.pointer(c_test)

  # 调用so文件中的c语言方法
  so.generate_points(ptr_test, 10000)
  ptr_test.contents.sentence = so.increment_string(ptr_test.contents.sentence, -5)
  so.distance_between_points(ptr_test)
  so.free(ptr_test.contents.points)
  so.free(ptr_test.contents.distances)
  print('ctypes run time: %s'%str(time.time() - start_time))